package org.easystub;

import java.lang.reflect.Proxy;

public class ProxyFactory {

    private final CglibProxyFactory cglibProxyFactory;

    public ProxyFactory() {
        this.cglibProxyFactory = new CglibProxyFactory();
    }

    public <T> T createProxyInstance(InvocationHandlerParameters<T> params) {
        T proxy;
        if(params.getStubbedClass().isInterface()) {
            proxy = jdkProxy(params);
        } else {
            proxy = cglibProxyFactory.createProxy(params);
        }

        params.getReporter().setReportingObject(proxy);
        return proxy;
    }

    @SuppressWarnings("unchecked")
    private <T> T jdkProxy(InvocationHandlerParameters<T> params) {
        return (T) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[]{params.getStubbedClass(), InvocationHandlerLocator.class},
                new StubInvocationHandler(params));
    }

}
